﻿using System;
using RaytracerLib.MathLib;
using YAXLib;

namespace RaytracerLib.Layers
{
    public abstract class ThresholdOperationLayer : UnaryLayer
    {
        protected double m_level_value;
        protected ColorFloat m_level_color;

        protected ThresholdOperationLayer(Layer a_childLayer)
            : base(a_childLayer)
        {
        }

        public override ColorFloat GetColor(Vector2 a_uv, Intersection a_intersection)
        {
            ColorFloat c = ChildLayer.GetColor(a_uv, a_intersection);
            return new ColorFloat(
                (c.R >= m_level_color.R) ? 1 : 0,
                (c.G >= m_level_color.G) ? 1 : 0,
                (c.B >= m_level_color.B) ? 1 : 0);
        }

        public override Tangents GetTangents(Vector2 a_uv, Vector2 a_tx, Vector2 a_ty,
            Intersection a_intersection)
        {
            throw new NotImplementedException();
        }

        public override double GetValue(Vector2 a_uv, Intersection a_intersection)
        {
            return (ChildLayer.GetValue(a_uv, a_intersection) >= m_level_value) ? 1 : 0;
        }
    }

    public class ThresholdColorOperationLayer : ThresholdOperationLayer
    {
        public ThresholdColorOperationLayer(Layer a_childLayer, ColorFloat a_level)
            : base(a_childLayer)
        {
            Level = a_level;
        }

        [YAXNode]
        public ColorFloat Level
        {
            get
            {
                return m_level_color;
            }
            set
            {
                m_level_color = value;
                m_level_value = m_level_color.Avg;
            }
        }

        public override void RenderStart(RenderStartPhase a_phase)
        {
            if (a_phase == RenderStartPhase.SRGBToLinear)
                Level = Gamma.SRGBToLinear(Level);

            base.RenderStart(a_phase);
        }
    }

    public class ThresholdValueOperationLayer : ThresholdOperationLayer
    {
        public ThresholdValueOperationLayer(Layer a_childLayer, double a_level)
            : base(a_childLayer)
        {
            Level = a_level;
        }

        [YAXNode]
        public double Level
        {
            get
            {
                return m_level_value;
            }
            set
            {
                m_level_value = value;
                m_level_color = new ColorFloat(value);
            }
        }
    }
}